package cn.tedu.boot.ers.service.impl;

import cn.tedu.boot.ers.entity.Table;
import cn.tedu.boot.ers.exception.ServiceException;
import cn.tedu.boot.ers.mapper.TableMapper;
import cn.tedu.boot.ers.pojo.dto.TableDTO;
import cn.tedu.boot.ers.pojo.dto.TableIsOverDTO;
import cn.tedu.boot.ers.pojo.dto.TableUpdateNameDTO;
import cn.tedu.boot.ers.pojo.vo.TableVO;
import cn.tedu.boot.ers.service.ITableService;
import cn.tedu.boot.ers.web.State;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TableServiceImpl implements ITableService {
    @Autowired
    TableMapper tableMapper;

    @Override
    public void AddNewTable(TableDTO tableDTO) {
        String name = tableDTO.getName();
        if(tableMapper.getTableByName(name)!=null){
            throw new ServiceException(State.ERR,"桌子名称（"+name+"）已经存在");
        }
        Table table = new Table();
        BeanUtils.copyProperties(tableDTO,table);

        table.setIsOver(0);
        int i = tableMapper.insertTable(table);
        if(i!=1){
            throw new ServiceException(State.ERR,"未知错误，请稍后再试");
        }

    }

    @Override
    public void updateIsOver(TableIsOverDTO tableIsOverDTO) {
        String name = tableIsOverDTO.getName();
        if(tableMapper.getTableByName(name).getIsOver()==tableIsOverDTO.getIsOver()){
            throw new ServiceException(State.ERR,"状态已经是（"+tableIsOverDTO.getIsOver()+")");
        }
        int i = tableMapper.updateIsOverByName(tableIsOverDTO);
        if(i!=1){
            throw new ServiceException(State.ERR,"未知错误，请稍后再试");
        }
    }

    @Override
    public void updateNameByName(TableUpdateNameDTO tableUpdateNameDTO) {
        String name = tableUpdateNameDTO.getNewName();
        if(tableMapper.getTableByName(name)!=null){
            throw new ServiceException(State.ERR,"桌子名称（"+name+"）已经存在");
        }
        int i = tableMapper.updateNameByName(tableUpdateNameDTO);
        if(i==0){
            throw new ServiceException(State.ERR,"未知的异常请稍后再试");
        }
    }

    @Override
    public List<TableVO> tableList() {
        List<TableVO> tableVOS = tableMapper.tableList();
        return tableVOS;
    }
}
